﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Microsoft.Practices.Unity;

namespace Silverlight.Weblog.Client.Default.Widgets.TwitterSiderbar
{
    public class TwitterTimeLineService : ITwitterTimeLineService
    {
        [Dependency]
        public ITwitterTimelineParser TwitterTimelineParser { get; set; }

        private const string PROXY_URL = "http://justinangel.cloudapp.net/Proxy.ashx?Url=";
        private const string TWITTER_TIMELINE_URL = "http://twitter.com/statuses/user_timeline/";
        private const string TWITTER_TIMELINE_URL_END = ".xml?count=60";

        #region Implementation of ITwitterInformationService

        public void GetUserTimeline(string Username)
        {
            string TwitterTimelineUrl = string.Format("{0}{1}{2}{3}", PROXY_URL, TWITTER_TIMELINE_URL, Username, TWITTER_TIMELINE_URL_END);

            WebClient client = new WebClient();

            client.DownloadStringCompleted += (s, args) =>
              {
                  if (args.Error == null)
                      RaiseTwitterTimelineReady(TwitterTimelineParser.Parse(args.Result));
              };

            client.DownloadStringAsync(new Uri(TwitterTimelineUrl));
        }

        public event TwitterTimelineEventHandler TwitterTimelineReady;

        private void RaiseTwitterTimelineReady(List<TwitterStatus> TwitterStatuses)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                TwitterTimelineEventHandler handler = TwitterTimelineReady;
                if (handler != null)
                    handler(this, new TwitterTimelineEventHandlerArgs(TwitterStatuses));
            });

        }

        #endregion
    }


}
